/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.app.hotelroom.service.impl;

import me.zhengjie.modules.app.hotel.service.dto.HotelInfoDto;
import me.zhengjie.modules.app.hotelroom.domain.HoteRoomInfo;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.app.hotelroom.repository.HoteRoomInfoRepository;
import me.zhengjie.modules.app.hotelroom.service.HoteRoomInfoService;
import me.zhengjie.modules.app.hotelroom.service.dto.HoteRoomInfoDto;
import me.zhengjie.modules.app.hotelroom.service.dto.HoteRoomInfoQueryCriteria;
import me.zhengjie.modules.app.hotelroom.service.mapstruct.HoteRoomInfoMapper;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.service.dto.UserDto;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Haojie Li
* @date 2021-03-02
**/
@Service
@RequiredArgsConstructor
public class HoteRoomInfoServiceImpl implements HoteRoomInfoService {

    private final HoteRoomInfoRepository hoteRoomInfoRepository;
    private final HoteRoomInfoMapper hoteRoomInfoMapper;

    @Override
    public Map<String,Object> queryAll(HoteRoomInfoQueryCriteria criteria, Pageable pageable){
    	//获取用户权限
		JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
		
		UserDto userDto = jwtUserDto.getUser();
		List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
		if(hotelLists.size() == 1) {
			criteria.setHoteId(hotelLists.get(0).getId().toString());
		}
        Page<HoteRoomInfo> page = hoteRoomInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(hoteRoomInfoMapper::toDto));
    }

    @Override
    public List<HoteRoomInfoDto> queryAll(HoteRoomInfoQueryCriteria criteria){
    	//获取用户权限
		JwtUserDto jwtUserDto = (JwtUserDto) SecurityUtils.getCurrentUser();
		
		UserDto userDto = jwtUserDto.getUser();
		List<HotelInfoDto> hotelLists = new ArrayList<HotelInfoDto>(userDto.getHotels());
		if(hotelLists.size() == 1) {
			criteria.setHoteId(hotelLists.get(0).getId().toString());
		}
        return hoteRoomInfoMapper.toDto(hoteRoomInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public HoteRoomInfoDto findById(String id) {
        HoteRoomInfo hoteRoomInfo = hoteRoomInfoRepository.findById(id).orElseGet(HoteRoomInfo::new);
        ValidationUtil.isNull(hoteRoomInfo.getId(),"HoteRoomInfo","id",id);
        return hoteRoomInfoMapper.toDto(hoteRoomInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HoteRoomInfoDto create(HoteRoomInfo resources) {
        resources.setId(IdUtil.simpleUUID()); 
        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        resources.setCreateTime(LocalDateTime.now());
        resources.setIsEnable(1);
        return hoteRoomInfoMapper.toDto(hoteRoomInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(HoteRoomInfo resources) {
    	resources.setUpdateBy(SecurityUtils.getCurrentUsername());
    	resources.setUpdateTime(LocalDateTime.now());
    	
        HoteRoomInfo hoteRoomInfo = hoteRoomInfoRepository.findById(resources.getId()).orElseGet(HoteRoomInfo::new);
        ValidationUtil.isNull( hoteRoomInfo.getId(),"HoteRoomInfo","id",resources.getId());
        hoteRoomInfo.copy(resources);
        hoteRoomInfoRepository.save(hoteRoomInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            hoteRoomInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<HoteRoomInfoDto> all, HttpServletResponse response) throws IOException {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list = new ArrayList<>();
        for (HoteRoomInfoDto hoteRoomInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("房间号", hoteRoomInfo.getRoomNo());
            map.put("房间名称", hoteRoomInfo.getRoomName());
//            map.put("所属酒店唯一标识", hoteRoomInfo.getHoteId());
            map.put("所属酒店名称", hoteRoomInfo.getHoteName());
            map.put("创建者", hoteRoomInfo.getCreateBy());
            map.put("更新者", hoteRoomInfo.getUpdateBy());
            map.put("创建时间", hoteRoomInfo.getCreateTime()  == null ? "" : dtf.format(hoteRoomInfo.getCreateTime()));
            map.put("更新时间", hoteRoomInfo.getUpdateTime() == null ? "" : dtf.format(hoteRoomInfo.getUpdateTime()));
            
            map.put("数据状态", hoteRoomInfo.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

	@Override
	public HoteRoomInfoDto findByHotelNo(String hoteId, String hotelRoomNo) {
		// TODO Auto-generated method stub
		HoteRoomInfo hoteRoomInfo = hoteRoomInfoRepository.findByHoteIdAndRoomNo(hoteId, hotelRoomNo);
		return hoteRoomInfoMapper.toDto(hoteRoomInfo);
	}

	@Override
	public boolean isExistByHotelNo(String hoteId, String hotelRoomNo) {
		// TODO Auto-generated method stub
		HoteRoomInfo hoteRoomInfo = hoteRoomInfoRepository.findByHoteIdAndRoomNo(hoteId, hotelRoomNo);
		return hoteRoomInfo == null ? false : true;
	}
}